package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.TravelContent;
import cn.wolfcode.trip.base.query.TravelQueryObject;
import cn.wolfcode.trip.base.service.INoticeService;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
/**
 * 游记资源控制器
 */
@Controller
@RequestMapping("travel")
public class TravelController {
    @Autowired
    private ITravelService travelService;
    @Autowired
    private INoticeService noticeService;


    @RequestMapping("list")
    public String list(@ModelAttribute("qo")TravelQueryObject qo, Model model){
        //待审核状态
        if (qo.getState()==null){
            qo.setState(Travel.STATE_TOAUDIT);
        }
        //设置排序方法
        qo.setOrderBy("t.lastUpdateTime");
        //设置公开
        qo.setIsPublic(true);
        model.addAttribute("pageInfo",travelService.queryReasonable(qo));
        return "travel/list";
    }

    @RequestMapping("releaseList")
    public String releaseList(@ModelAttribute("qo")TravelQueryObject qo, Model model){
        qo.setOrderBy("t.releaseTime desc");
        qo.setState(Travel.STATE_RELEASED);
        model.addAttribute("pageInfo",travelService.queryReasonable(qo));
        return "travel/releaseList";
    }

    /**
     * 审核游记,通过审核
     * @param travel
     * @return
     */
    @RequestMapping("updateState")
    @ResponseBody
    public JsonResult updateState(Travel travel){
        JsonResult jsonResult = new JsonResult();
        if (travel.getState()==2){//审核通过
            travel.setReleaseTime(new Date());
            //发通知,给作者
            noticeService.saveNoticeForAuthor(travel.getId());
        }
        try {
            travelService.updateState(travel);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.mark("操作失败!");
        }
        return jsonResult;
    }


    @RequestMapping("travelContent")
    @ResponseBody
    public TravelContent getTravelContent(Long id){
        return travelService.selectTravelContentById(id);
    }

}
